package com.aha.secondchapter.third;

import com.aha.secondchapter.first.MyQueue;
import com.aha.secondchapter.second.MyStack;

import java.util.Arrays;

/**
 * 小猫钓鱼
 * Created by wangxin on 2015/10/31.
 */
public class CatFishing {
    //TODO 这个游戏有肯能出现游戏无限循环无法结束的现象  谁都无法完全赢得对方的牌
    public static void main(String[] args) {
        CatFishing cf  = new CatFishing();
        MyQueue xiaoha = new MyQueue();
        int[] xhArr = new int[102];
        int[] xhNumArr = {2,4,1,2,5,6};
        System.arraycopy(xhNumArr,0,xhArr,0,xhNumArr.length);
        xiaoha.setData(xhArr);
        xiaoha.setHead(0);
        xiaoha.setTail(xhNumArr.length);
        MyQueue xiaoheng = new MyQueue();
        int[] xhhArr = new int[102];
        int[] xhhNumArr = {3,1,3,5,6,4};
        System.arraycopy(xhhNumArr,0,xhhArr,0,xhhNumArr.length);
        xiaoheng.setData(xhhArr);
        xiaoheng.setHead(0);
        xiaoheng.setTail(xhhNumArr.length);
        MyStack ms = new MyStack(new int[100]);

        while(!xiaoha.isEmpty() && !xiaoheng.isEmpty()) {
            //小哈先出牌 牌入栈
            ms.push(xiaoha.out());
            //判断是否能收牌;result>0代表在result这个位置到刚出牌的位置为赢得的牌插入手牌队列中
            int shResult = cf.isWin(ms);
            if (shResult >= 0) {
                while (ms.getTop() >= shResult)
                    xiaoha.in(ms.pop());
            }
            System.out.println("小哈手牌：" + Arrays.toString(xiaoha.getData()));
            System.out.println("桌上的牌："+Arrays.toString(ms.getData()));
            System.out.println("桌面top"+ms.getTop());
            //小哼出牌；同小哈出牌
            ms.push(xiaoheng.out());
            int xhResult = cf.isWin(ms);
            if (xhResult >= 0) {
                while (ms.getTop() >= xhResult)
                    xiaoheng.in(ms.pop());
            }
            System.out.println("小哼手牌：" + Arrays.toString(xiaoheng.getData()));
            System.out.println("桌上的牌："+Arrays.toString(ms.getData()));
            System.out.println("桌面top"+ms.getTop());
            System.out.println("****************");
        }
        if(xiaoha.isEmpty()){
            System.out.println("小哈 win! ");

        }else{
            System.out.println("小哼 win! ");

        }
        System.out.println("小哈手牌：" + Arrays.toString(xiaoha.getData()));
        System.out.println("小哼手牌：" + Arrays.toString(xiaoheng.getData()));
        System.out.println("桌上的牌："+Arrays.toString(ms.getData()));
    }

    /**
     * 判断是否可以赢得桌面上的牌
     * 循环遍历效果不好！！！
     * @param stack
     * @return
     */
    public int isWin(MyStack stack){
        if(stack.getTop()<1) return -1;
        int[] data = stack.getData();
        int len = stack.getTop();
        int p = stack.getTopData();
        for (int i = 0; i < len; i++) {
            //返回i+1为书中意思，表示收回的牌不包括匹配到的那张。例如 2,3,1,2收回的是牌顺序是 2,1,1
            //我理解应该全部收回这样需要改成放回i；即收回的牌及顺序为 2,1,3,2
            if(data[i] == p) return i+1;
        }
        return -1;
    }
}
